<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: 孤焰
  Date: 2021/6/2
  Time: 11:19
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>商品增加</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/layuiadmin/style/admin.css" media="all">

    <style>
        .layui-upload-img{width: 92px; height: 92px; margin: 0 10px 10px 0;}
    </style>
</head>
<body>

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-header">商品增加</div>
        <div class="layui-card-body" style="padding: 15px;">
            <form class="layui-form" action="">
                <div class="layui-form-item">
                    <label class="layui-form-label">商品类别</label>
                    <div class="layui-input-block">
                        <select name="categoryId">
                            <option value=""></option>
                            <c:forEach var="category" items="${categoryList}">
                                <option value="${category.id}">${category.name}</option>
                            </c:forEach>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">商品名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="name" lay-verify="required" autocomplete="off" placeholder="请输入商品名称"
                               class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">商品副标题</label>
                    <div class="layui-input-block">
                        <input type="text" name="subtitle" lay-verify="required" autocomplete="off" placeholder="请输入商品副标题"
                               class="layui-input">
                    </div>
                </div>

                <div class="layui-card">
                    <div class="layui-card-header">商品主图上传</div>
                    <div class="layui-card-body">
                        <div class="layui-upload">
                            <button type="button" class="layui-btn" id="mainImgUpload">上传图片</button>
                            <div class="layui-upload-list">
                                <img class="layui-upload-img" id="mainImg">
                                <p id="test-upload-demoText"></p>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="layui-card">
                    <div class="layui-card-header">商品详情图上传</div>
                    <div class="layui-card-body">
                        <div class="layui-upload">
                            <button type="button" class="layui-btn" id="subImgUpload">多图片上传</button>
                            <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                                预览图：
                                <div class="layui-upload-list" id="subImg"></div>
                            </blockquote>
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">商品价格</label>
                    <div class="layui-input-block">
                        <input type="text" name="price" lay-verify="price" autocomplete="off" placeholder="请输入商品价格"
                               class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">商品库存</label>
                    <div class="layui-input-block">
                        <input type="text" name="stock" lay-verify="stock" autocomplete="off" placeholder="请输入商品库存"
                               class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">商品状态</label>
                    <div class="layui-input-block">
                        <input type="checkbox" checked="" name="status" lay-skin="switch" lay-text="在售|下架">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">商品详情</label>
                    <div class="layui-input-block">
                        <div id="detail" style="margin-top: 50px"></div>
                    </div>
                </div>


                <div class="layui-form-item layui-layout-admin">
                    <div class="layui-input-block">
                        <div class="layui-footer" style="left: 0;">
                            <button class="layui-btn" lay-submit="" lay-filter="product-submit">立即提交</button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>


<script src="${pageContext.request.contextPath}/layuiadmin/layui/layui.js"></script>
<script src="${pageContext.request.contextPath}/static/js/wangEditor.js"></script>
<script src="${pageContext.request.contextPath}/static/js/axios.min.js"></script>
<script>
    layui.config({
        base: '${pageContext.request.contextPath}/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'form', 'laydate'], function () {
        var $ = layui.jquery;
        var admin = layui.admin;
        var element = layui.element
        var layer = layui.layer;
        var form = layui.form;
        var upload = layui.upload;

        var mainImgPath = '';
        var subImgPath = '';

        //普通图片上传
        upload.render({
            elem: '#mainImgUpload'
            ,url: '${pageContext.request.contextPath}/upload/layuiUpload'
            ,before: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    $('#mainImg').attr('src', result); //图片链接（base64）
                });
            },
            done: function(res){
                //如果上传失败
                if(res.code != 200){
                    return layer.msg('文件上传失败，请重新选择！');
                } else {
                    //上传成功
                    mainImgPath = res.data;
                }

            }
        });

        //多图片上传
        upload.render({
            elem: '#subImgUpload'
            ,url: '${pageContext.request.contextPath}/upload/layuiUpload'
            ,multiple: true
            ,before: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    $('#subImg').append('<img src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img">')
                });
            },
            done: function(res){
                //上传失败
                if (res.code != 200) {
                    return layer.msg('文件上传失败，请重新选择！');
                } else {
                    //上传成功
                    subImgPath += res.data + ',';
                }
            }
        });

        //wangEditor富文本编辑器配置
        var editor = new wangEditor('#detail');
        //自定义上传图片规则
        editor.config.customUploadImg = function (resultFiles, insertImgFn) {
            // resultFiles 是 input 中选中的文件列表
            // insertImgFn 是获取图片 url 后，插入到编辑器的方法
            var formData = new FormData();
            for (var i = 0; i < resultFiles.length; i++) {
                formData.append('files', resultFiles[i]);
            }

            axios.post('${pageContext.request.contextPath}/upload/wangEditorUpload', formData).then(function (res){
                var imgUrlList = res.data.data;
                for (var i = 0; i < imgUrlList.length; i++) {
                    // 上传图片，返回结果，将图片插入到编辑器中
                    insertImgFn(imgUrlList[i].url);
                }
            });
        };
        editor.config.height=600;
        editor.config.zIndex=500;
        editor.config.excludeMenus = ['video'];
        editor.config.uploadImgServer = '${pageContext.request.contextPath}/upload/wangEditorUpload';
        editor.config.uploadImgMaxSize = 10 * 1024 * 1024;
        editor.create();

        // 自定义表单验证
        form.verify({
            price: [/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/, '价格值不合法'],
            stock: [/^[1-9]\d*$/, '库存值必须为正整数']
        });

        /* 监听提交 */
        form.on('submit(product-submit)', function (data) {
            var product = data.field;
            delete product.file;

            // 校验类别
            if (!product.categoryId) {
                layer.msg('请选择类别', {icon: 5});
                return false;
            }

            // 校验主图
            if (!mainImgPath) {
                layer.msg('请上传商品主图', {icon: 5});
                return false;
            }

            // 校验详情图
            if (!subImgPath) {
                layer.msg('请上传商品详情图', {icon: 5});
                return false;
            }

            var detail = editor.txt.html();
            if (!detail) {
                layer.msg('请编写商品详情', {icon: 5});
                return false;
            }

            product.status = product.status == 'on' ? 1 : 2;
            product.mainImage = mainImgPath;
            product.subImages = subImgPath.substring(0, subImgPath.length - 1);
            product.detail = detail;

            axios.post('${pageContext.request.contextPath}/product/addProduct', product).then(function (res) {
                // TODO 添加成功之后跳转至商品列表页存在BUG 如果商品列表页存在 则需要手动刷新
                if (res.data.code == 200) {
                    top.layui.index.openTabsPage('${pageContext.request.contextPath}/product/productPage', "商品列表");
                } else {
                    layer.msg(res.data.message, {icon: 5});
                }
            });
            return false;
        });
    });
</script>
</body>
</html>
